/**
 * @type {Custom.IMiddlewareHandler}
 */
const errorHandler = (options = {}) => {
    return async(ctx, next) => {
        try {
            await next()
            const { body, status } = ctx
            const isNotFound = status === 404 && !body
            if (isNotFound) {
                ctx.success("资源未找到", status)
            }
        } catch (error) {
            let { status = 500, message } = error

            const parameterErrorKeywords = [
                "body",
                "query",
                "param"
            ]

            const isParameterError = parameterErrorKeywords.some(
                keyword => message.includes(keyword)
            )

            if (isParameterError) {
                status = 400
            }

            const isProd = ctx.app.env === "production"
            const isServerError = status === 500
            const isProdServerError = isProd && isServerError

            if (isProdServerError) {
                message = "服务端错误"
            }
            ctx.fail(message, status)
            ctx.app.emit("error", { message, status })
        }
    }
}

module.exports = errorHandler